package com.ruoyi.web.wx.utils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
/**
 * 自定义拦截器1
 *
 * @myblog    www.wolzq.com
 * @create    2016年9月20日
 */
public class URLInterceptor implements HandlerInterceptor {

    private Map<String, Integer> redisTemplate=new HashMap<String,Integer>();
    private static final Logger logger = LoggerFactory.getLogger("RequestLimitLogger");
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String token = request.getHeader("token");
        if(StringUtils.isNotEmpty(token)){
            int verify = JwtUtil.verify(token);
            if(verify ==1 ){
                return true;
            } else{
                //返回校验token结果
                returnJson(response);
                return false;
            }
        }else {
            returnJson(response);
            return false;
        }

    }
    private void returnJson(HttpServletResponse response) throws IOException {
        ServletOutputStream writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getOutputStream();
            Map<String, Object> result = new HashMap<>();
            result.put("status",403);
            result.put("message","Token invalid");
            result.put("data", null);
             String s = JSON.toJSONString(result);
            writer.print(s);
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if(writer != null){
                writer.close();
            }
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }


}